<template>
  <div class="register-container">
    <el-card class="register-card" shadow="always">
      <div class="register-header">
        <h2>用户注册</h2>
        <p>创建一个新账号以访问系统</p>
      </div>

      <el-form class="register-form" :model="registerForm" :rules="registerRules" ref="registerFormRef" @submit.prevent="handleRegister" size="large">

        <div v-if="errorMessage" class="form-error">
            <el-alert :title="errorMessage" type="error" show-icon center />
        </div>

        <el-form-item prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" :prefix-icon="User" clearable />
        </el-form-item>

        <el-form-item prop="enName">
          <el-input v-model="registerForm.enName" placeholder="请输入英文名 (可选)" clearable />
        </el-form-item>

        <el-form-item prop="birthday">
          <el-input v-model="registerForm.birthday" placeholder="格式：YYYY-MM-DD（可选）" clearable />
          <div style="color:#909399;font-size:12px;margin-top:6px">提示：手动输入生日，格式必须为 <code>YYYY-MM-DD</code></div>
        </el-form-item>


        <el-form-item prop="mobile">
          <el-input v-model="registerForm.mobile" placeholder="请输入手机号" clearable />
        </el-form-item>

        <el-form-item prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" :prefix-icon="Lock" show-password clearable />
        </el-form-item>

        <el-form-item prop="confirm">
          <el-input v-model="registerForm.confirm" type="password" placeholder="确认密码" :prefix-icon="Lock" show-password clearable />
        </el-form-item>

        <el-form-item>
          <el-button native-type="button" class="register-button" type="primary" :loading="loading" @click="handleRegister">
            {{ loading ? '注册中...' : '立即注册' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  <!-- 注册成功覆盖层 -->
  <div v-if="showSuccess" class="center-success-overlay" @click.self="closeSuccess">
    <div class="center-success-box">
      <div class="center-success-title">注册成功</div>
      <div class="center-success-message">{{ successMessage }}</div>
      <div class="center-success-actions">
        <el-button type="primary" size="small" @click="gotoLogin">前往登录</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { ElForm } from 'element-plus'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import api from '../utils/api'
import { useRouter } from 'vue-router'

const router = useRouter()

interface RegisterForm {
  username: string
  enName?: string
  mobile?: string
  email?: string
  password: string
  confirm: string
  birthday?: string | null
  // removed profileUrl and isActive per requirements
}

const registerFormRef = ref<InstanceType<typeof ElForm>>()
const loading = ref(false)
const errorMessage = ref('')

const registerForm = reactive<RegisterForm>({
  username: '',
  enName: '',
  mobile: '',
  email: '',
  password: '',
  confirm: '',
  birthday: null,
  // profileUrl and isActive removed
})

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 12, message: '用户名长度在 3 到 12 个字符', trigger: 'blur' }
  ],
  enName: [
    { required: false }
  ],
  birthday: [
    { required: false },
    { validator: (_rule: any, value: string, callback: any) => {
      if (!value) return callback()
      const dateRe = /^\d{4}-\d{2}-\d{2}$/
      if (!dateRe.test(String(value).trim())) callback(new Error('生日格式应为 YYYY-MM-DD'))
      else callback()
    }, trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的中国手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' }
  ],
  confirm: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: (_rule: any, value: string, callback: any) => {
      if (value !== registerForm.password) callback(new Error('两次输入的密码不一致'))
      else callback()
    }, trigger: 'blur' }
  ]
}

// 与登录页面共用的本地固定管理员用户名（保持同步）
// 已改为 panchenyang
const FIXED_ADMIN_USERNAME = 'panchenyang'

const handleRegister = async (): Promise<void> => {
  if (!registerFormRef.value) return

  try {
    const valid = await registerFormRef.value.validate()
    if (!valid) return

    loading.value = true
    // 防止注册时使用固定管理员用户名
    if (String(registerForm.username || '').trim().toLowerCase() === FIXED_ADMIN_USERNAME) {
      loading.value = false
      errorMessage.value = '该用户名为系统保留管理员账号，无法注册'
      ElMessage.error(errorMessage.value)
      return
    }

    // 先检查用户名是否已存在
    try {
      const checkResp: any = await api.get('/user/search', { params: { username: registerForm.username } })
      if (checkResp && checkResp.operationResult === 'SUCC') {
        errorMessage.value = '用户名已存在，请选择其他用户名'
        ElMessage.error(errorMessage.value)
        return
      }
    } catch (checkErr) {
      // 忽略检查失败，继续后续校验
      console.warn('用户名检查失败，继续尝试注册', checkErr)
    }

    // 检查邮箱/手机号唯一性（无单独接口时使用 /users 获取并比对）
    try {
      const usersResp: any = await api.get('/users')
      const list = Array.isArray(usersResp?.data) ? usersResp.data : (Array.isArray(usersResp) ? usersResp : [])
      if (list && list.length) {
        const foundEmail = list.find((u: any) => u.email && registerForm.email && u.email === registerForm.email)
        if (foundEmail) {
          errorMessage.value = '该邮箱已被注册，请使用其他邮箱'
          ElMessage.error(errorMessage.value)
          return
        }
        const foundMobile = list.find((u: any) => u.mobile && registerForm.mobile && u.mobile === registerForm.mobile)
        if (foundMobile) {
          errorMessage.value = '该手机号已被注册，请使用其他手机号'
          ElMessage.error(errorMessage.value)
          return
        }
      }
    } catch (errUsers) {
      console.warn('获取用户列表检查邮箱/手机号是否唯一时失败，继续尝试注册', errUsers)
    }

    // 调用后端注册接口（使用 Vite proxy），使用 await/try-catch 并打印更多诊断信息
    try {
    console.log('POST -> /api/user payload:', {
      userName: registerForm.username,
      password: registerForm.password,
      enName: registerForm.enName,
      mobile: registerForm.mobile,
      email: registerForm.email,
      birthday: registerForm.birthday
    })
    const resp: any = await api.post('/user', {
      userName: registerForm.username,
      password: registerForm.password,
      enName: registerForm.enName,
      mobile: registerForm.mobile,
      email: registerForm.email,
      birthday: registerForm.birthday
    })
      console.log('Register response:', resp)
      if (resp && resp.operationResult && resp.operationResult === 'SUCC') {
        // 显示成功提示覆盖层，短暂停留后跳转到登录页
        ElMessage.success(resp.errorMsg || '注册成功')
        errorMessage.value = ''
        successMessage.value = resp.errorMsg || '注册成功，请使用新账号登录'
        showSuccess.value = true
        // 1.5 秒后自动跳转
        setTimeout(() => {
          gotoLogin()
        }, 1500)
      } else {
        errorMessage.value = resp?.errorMsg || '注册失败，请稍后重试'
        ElMessage.error(errorMessage.value)
      }
    } catch (err: any) {
      console.error('Register error (await):', err)
      // 尝试输出底层请求路径（如果可用）
      const path = err?.response?.request?.path || err?.request?.path || err?.config?.url || ''
      console.warn('Request path seen by axios:', path)
  let serverMsg: any = err?.response?.data?.errorMsg ?? err?.response?.data ?? err?.message ?? ''
  if (typeof serverMsg === 'object') serverMsg = JSON.stringify(serverMsg)
  errorMessage.value = String(serverMsg) || '注册异常，请稍后重试'
  ElMessage.error(errorMessage.value)
    }
  } catch (error) {
    ElMessage.error('注册失败，请检查输入')
  } finally {
    loading.value = false
  }
}

const showSuccess = ref(false)
const successMessage = ref('')

const gotoLogin = () => {
  showSuccess.value = false
  try { router.push('/login') } catch (e) {}
}

const closeSuccess = () => {
  showSuccess.value = false
}
</script>

<style scoped>
.register-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.register-card {
  width: 100%;
  max-width: 480px;
}

.register-header {
  text-align: center;
  margin-bottom: 24px;
}

.register-header h2 {
  font-size: 1.6rem;
  margin-bottom: 8px;
}

.register-button {
  width: 100%;
  height: 44px;
  border-radius: 8px;
}

.form-error {
  display: flex;
  justify-content: center;
  max-width: 360px;
  margin: 0 auto 16px auto;
  padding: 4px 8px;
}

/* 注册成功覆盖层样式 */
.center-success-overlay {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.18);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}
.center-success-box {
  background: #fff;
  padding: 20px 24px;
  border-radius: 8px;
  width: 360px;
  box-shadow: 0 8px 24px rgba(0,0,0,0.12);
  text-align: center;
}
.center-success-title {
  font-weight: 700;
  color: #67c23a;
  margin-bottom: 8px;
}
.center-success-message { color: #606266; margin-bottom: 12px }
.center-success-actions { display: flex; justify-content: center }
</style>
